<template>
    <div id="app" v-wechat-title="$route.meta.title" :data-mode="girlsModel">
        <div class="socket-preview" :class="{'socket-preview-show':showPreviewMsg}" :data-msg="JSON.stringify(previewMsg)">
            <div class="socket-preview-icon">
                <svg class="socket-preview-svg" aria-hidden="true">
                    <use xlink:href="#icon-tijiaochenggong"></use>
                </svg>
            </div>
            <div class="socket-preview-context">收到一条消息</div>
        </div>
        <div class="view-blank">
            <keep-alive>
                <router-view v-if="$route.meta.keepAlive && isRouterAlive"></router-view>
            </keep-alive>
            <router-view v-if="!$route.meta.keepAlive && isRouterAlive"></router-view>
        </div>
        <div class="keyboard-blank"></div>
        <div class="map-background" id="mapBackground" v-if="!device.status"></div>
        <div class="full-screen-gifts" v-show="showGift">
            <div class="full-screen-gift-img">
                <img :src="giftImage">
            </div>
            <div class="full-screen-gift-text">{{giftName}}</div>
            <div class="full-screen-gift-from">{{fromName}} 送你礼物</div>
            <div class="full-screen-gift-close" @click="hideGift">
                <i class="cubeic-close"></i>

            </div>
        </div>
        <div class="share-controller" :class="{'share-controller-show':shareController.show}">
            <div class="share-mask" @click="hideShareController"></div>
            <div class="share-content">
                <div class="share-title">分享</div>
                <div class="share-list">
                    <div class="share-list-cell" @click="shareOnWechatSession" v-if="device.status">
                        <div class="share-list-cell-icon">
                            <svg class="svg-icon" aria-hidden="true">
                                <use xlink:href="#icon-weixin1"></use>
                            </svg>
                        </div>
                        <div class="share-list-cell-text">
                            微信好友
                        </div>
                    </div>
                    <div class="share-list-cell" @click="shareOnWechatTimeline" v-if="device.status">
                        <div class="share-list-cell-icon">
                            <svg class="svg-icon" aria-hidden="true">
                                <use xlink:href="#icon-pengyouquan"></use>
                            </svg>
                        </div>
                        <div class="share-list-cell-text">
                            朋友圈
                        </div>
                    </div>
                    <div class="share-list-cell">
                        <div class="share-list-cell-icon" @click="copyLink">
                            <svg class="svg-icon" aria-hidden="true">
                                <use xlink:href="#icon-lianjie"></use>
                            </svg>
                        </div>
                        <div class="share-list-cell-text">
                            复制链接
                        </div>
                    </div>
                </div>
                <div class="share-cancel" @click="hideShareController">取消</div>
            </div>
        </div>
    </div>

</template>
<script lang="ts">
    import {Component, Vue, Watch, Provide} from "vue-property-decorator";
    import {State, Action} from "vuex-class";
    import Scene from "@/render/Scene";
    import CommonUnit from "@/unit/CommonUnit";
    // import {State} from "@/store/dispatches"

    import {InterfaceSocket} from "@/interface/InterfaceSocket";
    import {InterfaceUser} from "@/interface/InterfaceUser";

    import AppAudio from "./service/AppAudio";
    import Http from "@/service/Http";
    import {changeNoReadCount, shareControllerToggle} from "@/store/dispatches";
    import WeixinServlet from "@/service/WeixinServlet";


    @Component({})
    export default class App extends Scene {
        private previewMsgTimer: number = 0;
        private pongTimer: number = 0;
        private showPreviewMsg: boolean = false;
        private oldPreviewMsg: any = {};
        private isRouterAlive: boolean = true;
        private geolocation: any = "";
        private giftImage: string = "";
        private giftName: string = "";
        private fromName: string = "";
        private showGift: boolean = false;
        private locationTime: number = 0;

        @State("UserStore")
        private user!: InterfaceUser;

        @State("ShareControllerStore")
        private shareController!: any;

        @State("SocketStore")
        private socket!: InterfaceSocket;

        @State("SettingStore")
        private setting!: any;

        @State("DeviceStore")
        private device!: any;

        @Action("sendMessage")
        private socketSendMessage!: Function;

        @Watch("socket.isConnected")
        private watchSocket(newVal: boolean) {
            if (newVal) {
                this.$nextTick(() => {
                    if (this.user.token) {
                        this.socketSendMessage(JSON.stringify({type: "bind", token: this.user.token}));
                    }
                    this.pongTimer = setInterval(() => {
                        this.socketSendMessage(JSON.stringify({type: "pong", timestamp: new Date().getTime()}));
                    }, 30000);
                });

            }
        }

        @Provide("reload")
        private reload(): void {
            this.isRouterAlive = false;
            this.$nextTick(() => {
                this.isRouterAlive = true;
            });
        }

        private get girlsModel(): string {
            if (this.setting.SoundAndShock.girlsModel) {
                document.getElementsByTagName("body")[0].className = "girls-model";
            } else {
                document.body.removeAttribute("class");
            }
            return String(this.setting.SoundAndShock.girlsModel);
        }

        private get previewMsg(): any {
            if (this.user.token != "") {
                if (!this.device.status) {
                    this.locationTime = this.locationTime + 1;
                    if (this.locationTime === 30) {
                        this.getCurrentPosition();
                        this.locationTime = 0;
                    }
                }
                Http.get(this.api.getTotalCountNoread, {}, {token: this.user.token}).then((res) => {
                    if (res.code === 1) {
                        changeNoReadCount(Number(res.data.count) > 99 ? 99 : Number(res.data.count));
                    } else {
                        changeNoReadCount(0);
                    }
                    this.changeNotificationBadge();
                }).catch((res) => {
                    changeNoReadCount(0);
                    this.changeNotificationBadge();
                });

            }
            if (this.device.status && this.setting.notification.hasOwnProperty(this.socket.message.type)) {
                if (this.socket.message.data.toid ! == this.user.userId) {
                    if (this.setting.SoundAndShock.messageShock) {
                        navigator.vibrate(200);
                    }
                    if (this.setting.SoundAndShock.messageSound) {
                        AppAudio.play("newMsg");
                    }
                }
            }


            if (this.socket.message.type != "error" && this.setting.notification[this.socket.message.type] === true) {
                if (String(this.socket.message.data.fromid) !== String(this.user.userId)) {
                    if (this.socket.message.type === "gift") {
                        this.showGift = true;
                        this.giftName = this.socket.message.data.gift.name;
                        this.giftImage = this.socket.message.data.gift.image.file_path;
                        this.fromName = this.socket.message.data.from_name;
                    } else {
                        clearTimeout(this.previewMsgTimer);
                        this.showPreviewMsg = true;
                        this.previewMsgTimer = setTimeout(() => {
                            this.showPreviewMsg = false;
                        }, 3000);
                        this.oldPreviewMsg = {
                            title: this.socket.message.type,
                            text: this.socket.message.msg
                        };
                        return this.oldPreviewMsg;
                    }
                }
            }
            return this.oldPreviewMsg;
        }

        private changeNotificationBadge() {
            this.$nextTick(() => {
                if (this.device.status) {
                    if (this.socket.noReadCount === 0) {
                        cordova.plugins.notification.badge.clear();
                    } else {
                        cordova.plugins.notification.badge.set(this.socket.noReadCount);
                    }
                }
            });
        }

        private mounted() {
            if (!this.device.status) {
                this.initLocation();
            }
        }

        private created() {
            //http://192.168.31.109:8080/www/?share=19&url=%2Faddress%2Flist%3Freferer%3DorderConfirm&from=timeline
            let query = this.getRequest(window.location.search);
            if (query.share) {
                window.location.replace(`${window.location.origin}${(<any> this).$router.options.base || ""}#/share?id=${query.share}&url=${encodeURIComponent(query.url)}`);
            } else {
                this.authentication();
            }
            this.$nextTick(() => {
                (<any> this).$connect();
                document.addEventListener("resume", () => {
                    if (!this.socket.isConnected) {
                        (<any> this).$connect();
                    }
                }, false);
            });
            if (CommonUnit.wechatBrowser()) {
                const weixin = new WeixinServlet(["updateAppMessageShareData", "chooseWXPay"], this.api.getWxConfig);
            }
        }

        private getRequest(str: string): any {
            let query: any = {};
            if (str.indexOf("?") != -1) {
                str = str.substr(1);
                let queryList: any = str.split("&");
                for (let i = 0; i < queryList.length; i++) {
                    query[(queryList as any)[i].split("=")[0]] = unescape(queryList[i].split("=")[1]);
                }
            }
            return query;
        }

        private initLocation(): void {
            let map = new AMap.Map("mapBackground", {
                resizeEnable: true
            });
            this.$nextTick(() => {
                AMap.plugin("AMap.Geolocation", () => {
                    this.geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true,//是否使用高精度定位，默认:true
                        timeout: 10000,          //超过10秒后停止定位，默认：5s
                    });
                    map.addControl(this.geolocation);
                    this.getCurrentPosition();
                });
            });
        }

        private getCurrentPosition() {
            if (this.geolocation !== "") {
                this.geolocation.getCurrentPosition((status: string, result: any) => {
                    if (status === "complete") {
                        this.getLocationSuccess(result);
                    } else {
                        this.getLocationFail(result);
                    }
                });
            }
        }

        private getLocationSuccess(result: any) {
            // alert(result);
            Http.post(this.api.saveUserLatLng, result.position, {token: this.user.token});
            // position: {P: 24.4809765625, Q: 118.04331841362898, lng: 118.043318, lat: 24.480977}
            // addressComponent: {citycode: "0592", adcode: "350205", businessAreas: Array(1), neighborhoodType: "", neighborhood: "", …}
            // formattedAddress: "福建省厦门市海沧区海沧街道泰地海西中心A座SEC泰地海西中心"
            //发送定位

        }

        private getLocationFail(result: any) {
            Http.post(this.api.saveUserLatLng, {lat: "", lng: ""}, {token: this.user.token});
        }

        private hideGift() {
            this.showGift = false;
        }

        private get shareMessage(): any {
            const sharaMessage: any = this.shareController.param;
            return {
                title: sharaMessage.title,
                description: sharaMessage.desc,
                thumb: sharaMessage.thumb,
                media: {
                    type: Wechat.Type.WEBPAGE,
                    webpageUrl: sharaMessage.link
                }
            };

        }

        private shareOnWechatSession() {
            Wechat.share({
                message: this.shareMessage,
                scene: Wechat.Scene.SESSION
            }, () => {
                (this as any).$createToast({
                    txt: "分享成功",
                    type: "correct"
                });
            }, (reason: any) => {
                (this as any).$createToast({
                    txt: "分享失败：" + String(reason),
                    type: "correct"
                });
            });
        }

        private shareOnWechatTimeline() {
            Wechat.share({
                message: this.shareMessage,
                scene: Wechat.Scene.TIMELINE
            }, () => {
                (this as any).$createToast({
                    txt: "分享成功",
                    type: "correct"
                }).show();
            }, (reason: any) => {
                (this as any).$createToast({
                    txt: "分享失败：" + String(reason),
                    type: "correct"
                }).show();
            });
        }

        private copyLink(): void {
            const sharaMessage: any = this.shareController.param;
            if (this.device.status) {
                cordova.plugins.clipboard.copy(sharaMessage.link);
            } else {
                const copy = require("copy-to-clipboard");
                copy(sharaMessage.link);
            }

            (this as any).$createToast({
                txt: "链接已复制",
                type: "correct"
            }).show();
            shareControllerToggle();
        }

        private hideShareController() {
            shareControllerToggle();
        }
    }

</script>
<style lang="stylus">
    @font-face {
        font-family: "lovely";
        src: url('/assets/fonts/lovely/lovely.TTF') /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
    }

    @font-face {
        font-family: "girl";
        src: url('/assets/fonts/girl/girl.ttf') /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
    }

    @import "/components/aui/style/compatible-safe-area.styl"

    body.girls-model, html.girls-model
        font-family girl

    #app
        overflow hidden;
        height 100vh;
        width 100vw;
        display flex;
        flex-direction column;

        #mapBackground
            opacity 0;
            height 0;
            width 0;

    .view-blank
        flex 1;
        display block;
        position relative;


    .keyboard-blank
        /*height 242px;*/
        /*flex 0 0 242px;*/
        width 100vw;

    .socket-preview
        position absolute;
        left 12px;
        right 12px;
        top calc(6px + var(--safe-area-inset-top));
        height 55px;
        background #fff;
        z-index 201;
        display flex;
        border-radius 5px;
        box-shadow rgba(210, 210, 210, .2) 0 0 10px 10px;
        justify-content center;
        align-items center;
        transform translateY(calc(-61px - var(--safe-area-inset-top))) scale(0)
        transition transform .3s ease-in-out;
        border 1px solid rgba(210, 210, 210, .5);

        .socket-preview-icon
            width 25px;
            height 25px;

            .socket-preview-svg
                width 25px;
                height 25px;


        .socket-preview-context
            padding-left 12px;
            display flex;
            flex-direction column;

    .socket-preview-show
        transform translateY(0) scale(1)


</style>
<style lang="stylus">
    @import "./assets/fonts/iconfont/iconfont.css";
    @import "~animate.css/animate.min.css"

    .svg-icon
        width: 1em;
        height: 1em;
        vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;

    #app
        font-size 14px;
        min-height 100vh;
        position relative;
        background-color rgba(255, 255, 255, 0);

    div.view, div.main, div.index
        transform translateZ(1);
        backface-visibility hidden;

    /*perspective 1000;*/


    div, p, textarea
        box-sizing border-box

    img
        content: normal !important;

    input, textarea
        outline: none;

    .ellipsis
        overflow hidden
        text-overflow ellipsis;
        white-space nowrap

    .ellipsis-2
        text-overflow ellipsis;
        overflow hidden;
        display -webkit-box;
        -webkit-box-orient vertical;
        -webkit-line-clamp 2;

    .clearfix
        &::before, &::after
            content '';
            display block;
            height 0;
            clear both;
            visibility hidden;


    //禁用默认的下拉刷新和边界效果,但是依然可以进行滑动导航
    body
        overscroll-behavior-y none;

    //全局无数据样式
    .no-data
        height 50px;
        font-size 13px;
        text-align center;
        line-height 50px;


    .amap-copyright
        display none !important;

    //全局flex布局
    .flex
        display flex;

    //左右浮动
    .rt
        float right;

    .lf
        float left;

    .hidden
        display none;

    .show
        display block !important;

    //骨架屏全局样式
    .skeleton-preview
        padding var(--safe-area-inset-top) 0 0 0;
        width 100vw;
        height 100vh;
        position absolute;
        z-index 112;

        img
            width 100vw;
            height calc(100vh - var(--safe-area-inset-top));


    .decimal-point
        font-size .8em;

    .mosaic
        filter: blur(20px);

    .scroll-safe-area-bottom
        height var(--safe-area-inset-bottom);
        width 100%;
        overflow hidden;
        background rgba(255, 255, 255, 0);


</style>
<style lang="stylus">
    .prefetch-font
        position absolute;
        left -100vw;
        bottom 100vw;

        .lovely-font
            font-family lovely;

        .girl-font
            font-family girl;

    .share-controller
        overflow hidden;
        z-index 400;
        position absolute;
        width 100vw;
        height 0;
        top 0;
        left 0;
        opacity 0;

        .share-mask
            width 100vw;
            height 100vh;
            background rgba(0, 0, 0, 0)
            transition background .3s ease-in-out

        .share-content
            width 100vw;
            position absolute;
            bottom 0;
            transform translateY(100%)
            transition transform .3s ease-in-out

            .share-title
                height: 40px;
                display flex;
                justify-content center;
                align-items center
                border-top-right-radius 10px;
                border-top-left-radius 10px;
                background rgba(232, 232, 232, .9);
                color #767676;

            .share-list
                padding-bottom 10px;
                display flex;
                background rgba(232, 232, 232, .9)

                .share-list-cell
                    width 57px;
                    margin 15px 0 10px 12px;

                    .share-list-cell-icon, .share-list-cell-text
                        display flex;
                        justify-content center;
                        align-items center

                    .share-list-cell-icon
                        font-size 42px;
                        height: 57px;
                        width 57px;
                        background #fff;
                        border-radius 10px;

                    .share-list-cell-text
                        height 30px;
                        font-size 12px;
                        margin-top 5px;

            .share-cancel
                height calc(57px + var(--safe-area-inset-bottom));
                padding-bottom var(--safe-area-inset-bottom);
                width 100vw;
                background #fff;
                display flex;
                justify-content center;
                align-items center;
                font-size 15px;
                color #333;

    .share-controller-show
        height 100vh;
        opacity 1;

        .share-mask
            background rgba(0, 0, 0, .3)

        .share-content
            transform translateY(0)

    .full-screen-gifts
        position absolute;
        background rgba(0, 0, 0, .3);
        width 100vw;
        height 100vh;
        z-index 500;
        display flex;
        flex-direction column;
        justify-content center;
        align-items center

        .full-screen-gift-img
            width 50vw;
            height auto;

            img
                width 50vw;
                height auto;

        .full-screen-gift-text
            line-height 2;
            font-size 19px;
            color #fff;
            margin-top 20px;

        .full-screen-gift-from
            margin-top 20px;
            line-height 1.77;
            padding 0 20px;
            color #fff;

        .full-screen-gift-close
            width 30px;
            height 30px;
            border-radius 30px;
            margin-top 40px;
            display flex;
            align-items center;
            color #fff;
            font-size 30px;
            justify-content center;


    .product-item
        display flex;
        flex-direction column;
        width calc(100% - 15px);
        margin-right 15px;
        position relative;
        padding-bottom 15px;
        margin-bottom 20px;
        background #fff;
        border-radius 5px;
        overflow hidden;

        .product-item-img
            width 100%;
            height calc(48vw - 15px);
            border-radius 3px;
            overflow hidden;
            display flex
            justify-content center;
            align-items center;


            img
                max-width calc(48vw - 15px);
                width auto;
                max-height calc(48vw - 15px);
                height auto;

        .product-item-title
            margin 5px 0;
            line-height 20px;
            padding 0 5px;
            max-height 40px;
            font-size 13px;

        .product-item-price
            display flex;
            align-items center;
            justify-content space-between;
            padding 0 5px;
            font-size 12px;


            .product-item-price-box
                span
                    &::before
                        content '￥'
                        margin-right -2px;
                        font-size 11px;

                .now-price
                    color $product-price-color;
                    font-size 15px;

                .line-price
                    padding-left 4px;
                    color #aaa;
                    text-decoration line-through;
                    font-size 11px

            .product-item-sale
                color #666

    .select-drawer
        position fixed;
        width 100%;
        height 100%
        right: 0;
        top 0;
        z-index 100;
        display flex;
        flex-direction row-reverse;
        &.hide
            width 0;
            .select-drawer-mask
                width 0;
            .select-drawer-content
                transform translateX(100%)

        .select-drawer-mask
            position fixed;
            width 100%;
            height 100%
            top: 0;
            left 0;
            background rgba(0, 0, 0, .7);


        .select-drawer-btn
            margin 10px 30px 0 30px;
            height: 40px;
            display flex;
            justify-content center;
            align-items center;
            background #ec6786;
            color #fff;
            border-radius 3px;

            &.select-drawer-btn-cancel
                background #aaaaaa

        .select-drawer-content
            width: 75vw;
            height 100vh;
            background #fff;
            z-index 101
            transition transform  .3s ease-in

            .select-drawer-content-title

                height 44px;
                width: 75vw;
                padding-top var(--safe-area-inset-top);
                display flex;
                justify-content center
                align-items center
                box-sizing content-box
                color #333;
                border-bottom 1px solid #dedede;

            .content-box
                background-color #fff;

                > div
                    padding 15px;
                    border-bottom 1px solid $theme-line-color;
                    justify-content: space-between;

                    i.icon-youbian
                        color $theme-viceColor-font;
                        padding-left 6px;


</style>
<!--dialog自定义插槽样式-->
<style lang="stylus">
    .face-needing-title-img
        width 72vw;
        background-image url("/assets/images/face-upload-needing.png");
        background-size cover;
        height 52vw;
        line-height 1.5

    .face-needing-content
        text-align: center;
        line-height 1.3
</style>
